import { Form, Input, Modal, message } from 'antd'
import React, { useState } from 'react'
import { GlobalFormLayout } from '@/layouts/Form'
import request from '@/utils/request'

const SceneMap = {
  HTTP_CALL_REQUEST_URL: 'HTTP调用_请求地址',
}

function CreateEndpointModal({ visible, onCancel, form, onOk, scene }) {
  const { getFieldDecorator, validateFields } = form
  const [loading, setLoading] = useState(false)
  const handleSave = () => {
    validateFields((err, data) => {
      if (err)
        return

      setLoading(true)
      request
        .post('/serverEndpoint/create', { data })
        .then(() => {
          message.success('添加成功')
          onCancel()
          onOk()
        })
        .finally(() => {
          setLoading(false)
        })
    })
  }
  return (
    <Modal
      title="添加端点"
      visible={visible}
      onCancel={onCancel}
      onOk={handleSave}
      okButtonProps={{ loading }}
      destroyOnClose
    >
      <Form {...GlobalFormLayout}>
        <Form.Item label="端点名称">
          {getFieldDecorator('endpointName', {
            rules: [
              {
                required: true,
                message: '端点名称不能为空',
              },
            ],
          })(<Input placeholder="请输入端点名称" onPressEnter={handleSave} />)}
        </Form.Item>
        <Form.Item label="端点URL">
          {getFieldDecorator('endpointUrl', {
            rules: [
              {
                required: true,
                message: '端点URL不能为空',
              },
            ],
          })(<Input placeholder="请输入端点URL" onPressEnter={handleSave} />)}
        </Form.Item>
        <Form.Item label="应用场景">
          {getFieldDecorator('sceneName', {
            initialValue: SceneMap[scene],
          })(<Input disabled />)}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('scene', {
            initialValue: scene,
          })(<Input disabled hidden />)}
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default Form.create()(CreateEndpointModal)
